package view;

import javax.swing.*;
import java.awt.*;
import model.Book;
import dao.BookDAO;

public class EditBookDialog extends JDialog {
    private JTextField titleField;
    private JTextField authorField;
    private JTextField priceField;
    private JTextField stockField;
    private BookPanel bookPanel;
    private Book book;
    
    public EditBookDialog(JFrame parent, BookPanel bookPanel, Book book) {
        super(parent, "编辑图书", true);
        this.bookPanel = bookPanel;
        this.book = book;
        
        setLayout(new GridLayout(5, 2, 5, 5));
        
        // 添加输入框
        add(new JLabel("书名："));
        titleField = new JTextField(book.getTitle());
        add(titleField);
        
        add(new JLabel("作者："));
        authorField = new JTextField(book.getAuthor());
        add(authorField);
        
        add(new JLabel("价格："));
        priceField = new JTextField(String.valueOf(book.getPrice()));
        add(priceField);
        
        add(new JLabel("库存："));
        stockField = new JTextField(String.valueOf(book.getStock()));
        add(stockField);
        
        // 添加按钮
        JButton saveBtn = new JButton("保存");
        JButton cancelBtn = new JButton("取消");
        
        saveBtn.addActionListener(e -> updateBook());
        cancelBtn.addActionListener(e -> dispose());
        
        add(saveBtn);
        add(cancelBtn);
        
        pack();
        setLocationRelativeTo(parent);
    }
    
    private void updateBook() {
        try {
            String title = titleField.getText();
            String author = authorField.getText();
            double price = Double.parseDouble(priceField.getText());
            int stock = Integer.parseInt(stockField.getText());
            
            book.setTitle(title);
            book.setAuthor(author);
            book.setPrice(price);
            book.setStock(stock);
            
            BookDAO dao = new BookDAO();
            if (dao.updateBook(book)) {
                JOptionPane.showMessageDialog(this, "更新成功！");
                bookPanel.refreshTable();
                dispose();
            } else {
                JOptionPane.showMessageDialog(this, "更新失败！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "请输入有效的数字！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
} 